package com.gjy.util.basic;

import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;

import javax.script.ScriptEngine;
import javax.script.ScriptEngineManager;
import javax.script.ScriptException;

/**
 * @author gjy
 * @version 1.0
 * @since 2025-06-19 09:42:04
 */
public class JSUtil {

    private static final Logger log = LogManager.getLogger(JSUtil.class);
    private static final ScriptEngine engine = new ScriptEngineManager().getEngineByName("javascript");

    public static synchronized Object eval(String script) throws ScriptException {
        log.info("JS: {}", script);
        return engine.eval(script);
    }

    public static synchronized Object eval(String script, Object... bindings) throws ScriptException {
        if (bindings != null && bindings.length % 2 == 0) {
            for (int i = 0; i < bindings.length; i += 2) {
                engine.put(bindings[i].toString(), bindings[i + 1]);
            }
        }
        return engine.eval(script);
    }

}
